package com.thlws.study.rabbitmq.config;

import com.thlws.study.rabbitmq.internal.RmqConst;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author HanleyTang 2019-06-30
 */
@Configuration
public class RabbitConfig {

    private final RabbitTemplate rabbitTemplate;

    public RabbitConfig(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(){
        return new RabbitAdmin(rabbitTemplate);
    }

//    @Bean
//    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
//        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
//        factory.setConnectionFactory(connectionFactory);
//        factory.setMessageConverter(new Jackson2JsonMessageConverter());
//        //开启手动 ack ,等同配置 acknowledge-mode: manual
//        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
//        return factory;
//    }


    /**
     * 死信队列-Queue
     */
    @Bean
    public Queue dlxQueue(){

//        Map<String, Object> args = new HashMap<String, Object>();
//        args.put("x-dead-letter-exchange",dead_letter_exchange);
//        args.put("x-dead-letter-routing-key",dead_letter_routing_key);
//        return new Queue(dead_letter_queue, true, false, false, args);

//        return QueueBuilder.durable(dead_letter_queue)
//                .withArgument("x-dead-letter-exchange", dead_letter_exchange)
//                .withArgument("x-dead-letter-routing-key", dead_letter_routing_key)
//                .build();

        return QueueBuilder.durable(RmqConst.dead_letter_queue)
                .build();
    }


    /**
     * 死信队列-Exchange
     */
    @Bean
    public Exchange dlxExchange(){
        Exchange exchange = new TopicExchange(RmqConst.dead_letter_exchange);
        return exchange;
    }

    /**
     * 绑定死信队列和Exchange
     */
    @Bean
    public Binding bind(@Qualifier("dlxQueue") Queue dlxQueue,
                     @Qualifier("dlxExchange") Exchange dlxExchange){
        return BindingBuilder.bind(dlxQueue).to(dlxExchange).with(RmqConst.dead_letter_routing_key).noargs();
    }




}
